package com.zeros.latte.ui;

import android.content.Context;
import android.support.v7.app.AppCompatDialog;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;

import com.wang.avi.AVLoadingIndicatorView;
import com.zeros.latte.R;
import com.zeros.latte.util.DimenUtil;

import java.util.ArrayList;

/**
 * loading方法 on 2018/1/31.
 */

public class LatteLoader {

    private static final int LOADER_SIZE_SCALE = 8; //缩放比例
    private static final int LOADER_OFFSET_SCALE = 10;//偏移量
    private static final ArrayList<AppCompatDialog> LOADERS = new ArrayList<>();//存储loading

    //    默认loading
    private static final String DEFAULT_LOADER = LoaderStyle.BallClipRotatePulseIndicator.name();


    /**
     * 1.获取默认loading
     *
     * @param context:dialog类最好传入当前context，如果传入getapplicationContext在webview等一般会报错
     */
    public static void showLoading(Context context) {
        showLoading(context, DEFAULT_LOADER);
    }


    /**
     * 2.自定义loading
     *
     * @param type:枚举
     */
    public static void showLoading(Context context, Enum<LoaderStyle> type) {
        showLoading(context, type.name());
    }

    /**
     * 显示loading
     */
    public static void showLoading(Context context, String type) {

//        尽量用AppCompatDialog考虑兼容性
        final AppCompatDialog dialog = new AppCompatDialog(context, R.style.dialog);

        final AVLoadingIndicatorView avLoadingIndicatorView = LoaderCreator.create(type, context);
        dialog.setContentView(avLoadingIndicatorView);

//        屏幕宽高
        int deviceWidth = DimenUtil.getScreenWidth();
        int deviceHeight = DimenUtil.getScreenHeight();

        final Window dialogWindow = dialog.getWindow();

        if (dialogWindow != null) {
            final WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = deviceWidth / LOADER_SIZE_SCALE;
            lp.height = deviceHeight / LOADER_SIZE_SCALE;
            lp.height = lp.height + deviceHeight / LOADER_OFFSET_SCALE;
            lp.gravity = Gravity.CENTER;
        }
        LOADERS.add(dialog);//存储loading
        dialog.show();
    }

    /**
     * 停止loading
     */
    public static void stopLoading() {
        for (AppCompatDialog dialog : LOADERS) {
            if (dialog != null) {
                if (dialog.isShowing()) {
                    dialog.cancel();//有回调
//                    dialog.dismiss();//单纯取消
                }
            }
        }
    }

}
